package com.yang.ddz.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by zongx on 2020/1/6.
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame request = (TextWebSocketFrame) msg;
            String receiveMsg = request.text();

            System.out.println("websocketServer 收到信息： " + receiveMsg);


            if (StringUtils.isNotBlank(receiveMsg)) {
                JSONObject jsonObject = JSON.parseObject(receiveMsg);
                System.out.print(jsonObject);
                String op = jsonObject.getString("op");
                switch (op) {
                    case "login":
                        jsonObject.put("message", "登录成功");
                        break;
                    //通知当前服务邀请
                    case "add":
                        jsonObject.put("message", "增加成功");
                        break;
                    //通知当前服务邀请
                    case "del":
                        jsonObject.put("message", "删除成功");
                        break;
                    //通知当前服务邀请
                    case "update":
                        jsonObject.put("message", "更新成功");
                        break;
                    //通知当前服务邀请
                    case "select":
                        jsonObject.put("message", "查找成功");
                        break;
                }
                String s = jsonObject.toJSONString();
                TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(s);
                ctx.channel().writeAndFlush(textWebSocketFrame);
            }

        }
    }
}